<?php
abstract class CC_Controller extends Zend_Controller_Action
{
    /** 
     * @var Doctrine\ORM\EntityManager 
     */
    protected $_em;
    /** 
     * @var Bisna\Service\Loader\DefaultLoader 
     */
    protected $_serviceLoader;
    
    public function init()
    {
        parent::init();
        
        $this->_em = Zend_Registry::get('doctrine')->getEntityManager();
        
        $this->_initDefaultJavascript();
        $this->_initDefaultCss();
        $this->_initServiceLoader();
    }
    
    public function preDispatch()
    {
        parent::preDispatch();
        
        $moduleName = $this->getRequest()->getModuleName();
        $controllerName = $this->getRequest()->getControllerName();
        $actionName = $this->getRequest()->getActionName();
        
        Zend_Registry::set('moduleName', $moduleName);
        Zend_Registry::set('controllerName', $controllerName);
        Zend_Registry::set('actionName', $actionName);
        
        $this->_checkFlagFlippers();
    }
    
	/**
     * Gets the current page. Convenience method for using
     * paginators
     * 
     * @param int $default 
     * @access protected
     * @return int
     */
    protected function _getPage($default = 1){
        $page = $this->_getParam('page');
        if (!$page || !is_numeric($page)) {
            return $default;
        }
        
        return $page;
    }
    
	/**
     * Queries the Flag and Flipper and redirects the user to a different
     * page if he/her doesn't have the required permissions for
     * accessing the current page
     * 
     * @access protected
     * @return void
     */
    protected function _checkFlagFlippers() 
    {
        $groups = array();
        $isAllowed = false;
        $isDebug = false;
        $controllerName = Zend_Registry::get('controllerName');
        $actionName = Zend_Registry::get('actionName');
        
        $auth = Zend_Auth::getInstance();
        
        if($auth->hasIdentity())
        {
            $user = $this->_em->getRepository('CC\Entity\User')->findOneByEmail($auth->getIdentity());
            $groups = $this->_em->getRepository('CC\Entity\User')->getGroupNameArray($user->getId());
        }
        else
        {
            $groups[] = 'guests';
        }
        
        /*if(Zend_Registry::get('IS_DEVELOPMENT') && $controllerName != 'error')
        {
            $flagModel = new Flag();
            
            $flag = strtolower(CURRENT_MODULE) . '-' . $controllerName;
            
            if(!$flagModel->checkRegistered($flag, CC_Inflector::camelCaseToDash($actionName))){
                $params = array(
                    'originalController' => $controllerName,
                    'originalAction' => $actionName
                );
                
                $this->_forward('flagflippers', 'error', NULL, $params);
                return;
            }
        }*/
        
        //Check the flag and flippers for ZFDebug
        foreach($groups as $group)
        {
            if(CC_FlagFlippers_Manager::isAllowed($group, 'testing', 'zfdebug'))
            {
                $isDebug = true;
                //Zend_Controller_Front::getInstance()->unregisterPlugin('ZFDebug_Controller_Plugin_Debug');
            }
            
            if(CC_FlagFlippers_Manager::isAllowed($group, $controllerName, $actionName))
            {
                $isAllowed = true;
            }
        }
        
        if(!$isDebug)
        {
            Zend_Controller_Front::getInstance()->unregisterPlugin('ZFDebug_Controller_Plugin_Debug');
        }
        
        if(!$isAllowed)
        {
            if(isset($user))
                return $this->_redirect('/backoffice/error/forbidden');
            
            // @TODO: the user is a guest, save the request and redirect him to the login page
            return $this->_redirect('/backoffice/users/login/');
        }
    }
    
    protected function _initDefaultJavascript()
    {
        $jquery = $this->view->jQuery();
        $jquery->enable();
        
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/ddpng.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/hoverIntent.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/superfish.js');
        $this->view->headScript()->appendFile($this->view->baseUrl() . '/js/backoffice.js');
    }
    
    protected function _initDefaultCss()
    {
        $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/css/backoffice.css');
        $this->view->headLink()->appendStylesheet($this->view->baseUrl() . '/css/superfish.css');
    }
    
    protected function _initServiceLoader()
    {
    	$configDir      = APPLICATION_PATH . '/configs';
        $serviceLocator = $configDir . '/serviceLocator.ini';
        $services       = $configDir . '/services.ini';
        $doctrine       = $configDir . '/application.ini';

        $context   = new \Bisna\Service\Context\IniFileContext(array(
            'path' => $services
        ));
        
        $d2Config  = new \Zend_Config_Ini($doctrine, APPLICATION_ENV);
        $container = new \Bisna\Application\Container\DoctrineContainer(
            $d2Config->resources->doctrine->toArray()
        );

        $locator   = new Bisna\Service\ServiceLocator($context, $container);
        $loader    = new Bisna\Service\Loader\DefaultLoader($locator);
    	
        $this->_serviceLocator = $locator;
    }
}
